<template>
  <view class="checkout-page">
    <view class="search-bar">
      <view style="display: flex; align-items: center;">
        <uni-search-bar ref="searchBar" v-model="searchVal"   cancelButton="none" clearButton="none" @confirm="onSearch" placeholder="条码/名称/货号" bgColor="#fff" style="flex: 1;"></uni-search-bar>
        <view @click="startScan" style="width: 80px;height: 75px;display: flex; align-items: center; justify-content: center;background-color: #007aff;">
          <image style="width: 50px;height: 50px;" src="/static/icon/扫码.png"></image>
        </view>
      </view>
    </view>
    <!-- 商品列表头部 -->
    <view class="product-header">
      <view class="header-item name-code">商品/条形</view>
      <view class="header-item">数量</view>
      <view class="header-item">单价</view>
      <view class="header-item">小计</view>
    </view>
    <!-- 主体内容容器 -->
    <view class="content-container">
       <view v-if="products.length > 0" class="product-list">
           <view v-for="(item, index) in products" :key="index" class="product-item" @tap="showProduct(index)">
             <view class="product-info">
               <view class="product-name">{{ item.productName }}</view>
               <view class="product-code" style="color:#a4a4a4;">{{ item.barcode }}</view>
             </view>
             <view class="product-quantity">x{{ item.qutity }}</view>
             <view class="product-price">¥{{ formatAmount(item.retailPrice) }}</view>
             <view class="product-total">¥{{ formatAmount(item.total) }}</view>
           </view>
         </view>
         <ProductPopup
           :visible="popupVisible"
           :productName="selectedProductName"
           :qutity="selectedQutity"
           :retailPrice="selectedRetailPrice"
           :index="selectedIndex"
           @update:visible="popupVisible = $event"
           @remove="removeProduct"
           @confirm="updateQutity"
         />
      <!-- 清空商品按钮 -->
      <view v-if="products.length > 0" class="summary">
        <view class="total-products">共 {{ totalProducts }} 件商品</view>
        <view @click="clearProducts" class="clear-button">清空商品</view>
      </view>
      <!-- 订单备注 -->
      <view v-if="products.length > 0" class="order-notes">
        <input v-model="orderNotes" placeholder="添加订单备注" />
      </view>
      <!-- 扫码提示区域 -->
      <view v-if="products.length === 0" class="pull-down-scan" @click="startScan">
        <view><image src="/static/icon/下箭头.png" mode="aspectFit"></image></view>
        <view><text>点击屏幕 扫码开单</text></view>
      </view>
      <!-- 当没有商品时显示的提示 -->
      <view v-if="products.length === 0" class="no-products-tip">
        暂无商品，请点击屏幕扫码添加商品。
      </view>
    </view>

    <!-- 固定在页面底部的 footer -->
    <view class="footer">
      <button class="delivery-method"  @click="handleDeliverySelection('/pages/distribution-home/distribution-home')">选择配送方式</button>
      <button class="settlement" @click="togglePopup">结算：¥{{ formatAmount(totalAmount) }}</button>
    </view>
	<Pay @payment-success="handlePaymentSuccess" :showPopup="showPopup" :totalAmount="totalAmount" :totalProducts="totalProducts" @close="togglePopup" :orderDetails="products" :orderRemark="orderNotes"></Pay>
  </view>
</template>

<script setup>
import { ref,computed,onMounted,watch  } from 'vue';
import Pay from'../component/pay.vue'
import ProductPopup from'../component/ProductPopup.vue'
import store from '../../store';

//这是点击商品的弹出框声明和方法
const popupVisible = ref(false);
const selectedIndex = ref(null);
const selectedProductName = ref('');
const selectedQutity = ref(0);
const selectedRetailPrice = ref(0);

function showProduct(index) {
  const product = products.value[index];
  selectedIndex.value = index;
  selectedProductName.value = product.productName;
  selectedQutity.value = product.qutity; // 确保这里使用的是 qutity 字段
  selectedRetailPrice.value = product.retailPrice;
  popupVisible.value = true;
}

function removeProduct(index) {
	const productId = products.value[index].productId;
	console.log("移除productId:",productId)
	store.dispatch('removeProduct', productId); // 调用 Vuex action 移除商品
  // products.value.splice(index, 1);
}

function updateQutity({ index, qutity }) {
  products.value[index].qutity = qutity;
  products.value[index].total = qutity * products.value[index].retailPrice; // 计算单个商品的小计
}


// 声明搜索框的值
const searchVal = ref('');
const showPopup = ref(false);
const togglePopup = () => {
	console.log('当前弹窗状态:', showPopup.value);
	  console.log('商品数量:', products.value.length);
	  if (!showPopup.value) { // 如果弹窗未打开
	    if (products.value.length > 0) {
	      showPopup.value = true;
	    } else {
	      uni.showToast({
	        title: '请添加收银商品',
	        icon: 'error',
	        duration: 2000
	      });
	    }
	  } else { // 如果弹窗已打开，直接关闭
	    showPopup.value = false;
	  }
};
const products = ref([
  // {
  //   productName: '优酸乳饮料–蓝莓味',
  //   barcode: '6900000000000',
  //   qutity: 2,
  //   retailPrice: 3.00,
  //   total: 0
  // }
]);
// 在组件挂载时从 Vuex 获取 searchCart 数据并合并到 products
onMounted(() => {
  mergeSearchCartToProducts();
});
// 合并 searchCart 到 products
const mergeSearchCartToProducts = () => {
  const searchCart = store.getters.getProducts;
  searchCart.forEach(searchProduct => {
    let existingProductIndex = products.value.findIndex(p => p.barcode === searchProduct.barcode);

    if (existingProductIndex !== -1) {
      // 如果找到了，更新数量和总价
      products.value[existingProductIndex].qutity += searchProduct.qutity;
      updateProductTotal(products.value[existingProductIndex]);
    } else {
      // 如果没有找到，添加新产品
      products.value.push({
        productName: searchProduct.productName,
        barcode: searchProduct.barcode,
        qutity: searchProduct.qutity,
        retailPrice: searchProduct.retailPrice,
        total: searchProduct.qutity * searchProduct.retailPrice,
        productId: searchProduct.productId,
        productImageUrl: searchProduct.productImageUrl
      });
    }
  });
  console.log('Merged Products:', products.value);
};
// 监听 Vuex 中 searchCart 的变化，实时合并数据
    watch(() => store.getters.getProducts, (newVal) => {
      products.value = []; // 清空现有商品列表
      mergeSearchCartToProducts(); // 重新合并新的商品列表
    }, { deep: true });

// 更新每个商品的小计
products.value.forEach(item => {
  item.total = (item.qutity * item.retailPrice);
});

const orderNotes = ref('');
const totalProducts = computed(() => products.value.length);
const totalAmount = computed(() => products.value.reduce((acc, curr) => acc + parseFloat(curr.total), 0));

// 更新每个商品的小计
function updateProductTotal(product) {
  product.total = (product.qutity * product.retailPrice).toFixed(2);
}

async function onSearch(event) {
  const query = event.value;
  console.log(query)
  if (!query) return;
  try {
    // 发请求获取商品信息192.168.129.92
    const response = await uni.request({
      url: `http://localhost:15000/PRODUCT-SERVICE/product/search?query=${encodeURIComponent(query)}`,
      method: 'GET'
    });
	const data = response.data;
	console.log(data)
	// 如果数据库中没有查询到商品
	if (data.length === 0) {
	  uni.showToast({
	    title: '未找到该商品',
	    icon: 'none', // 显示无图标的提示框
	    duration: 2000 // 提示框显示的持续时间
	  });
	  return;
	}
	// 将返回的数据转换为所需的格式
	const newProducts = data.map(product => ({
	  productName: product.productName,
	  barcode: product.barcode,
	  qutity: 1,
	  retailPrice: product.retailPrice,
	  total:product.retailPrice , // 默认总价等于单价乘以数量
	  productId: product.productId, // 保留原始ID以便后续操作
	  productImageUrl:product.productImageUrl
	}));
	  // 合并新旧数据，去重（基于barcode）
	newProducts.forEach(newProduct => {
	     // let existingProductIndex = products.value.findIndex(p => p.barcode === newProduct.barcode);
	     // 	    if (existingProductIndex !== -1) {
	     // 	        // 如果找到了，更新数量和总价
	     // 	        products.value[existingProductIndex].qutity += 1;
	     // 	        updateProductTotal(products.value[existingProductIndex]);
	     // 	    } else {
	     // 	        // 如果没有找到，添加新产品
	     // 	        products.value.push(newProduct);
	     // 	    }
		 store.dispatch('addProduct', newProduct);

	});
	console.log(response)
  } catch (error) {
    console.error('Failed to fetch product:', error);
  }
}
//清空商品
function clearProducts() {
  wx.showModal({
    title: '提示',
    content: '确定清空商品？',
    success(res) {
      if (res.confirm) {
        // 用户点击了确定按钮
        products.value = [];
        orderNotes.value = '';
        searchVal.value = ''; // 清空搜索框内容
        store.dispatch('clearProducts'); // 清空 Vuex 中的 products 并同步到本地存储
        // totalProducts.value = 0;
        // totalAmount.value = 0;
      } else if (res.cancel) {
        console.log('用户点击了取消');
      }
    },
    fail(err) {
      console.error('调用 showModal 方法失败', err);
    }
  });
}

// 金额格式化函数
const formatAmount = (value) => {
  return Number(value).toFixed(2);
};

// 开始扫描的方法
async function startScan() {
  try {
    const res = await new Promise((resolve, reject) => {
      uni.scanCode({
        scanType: ['barCode', 'qrCode'], // 指定扫码类型
        success: resolve,
        fail: reject
      });
    });
    console.log('Scan result:', res.result);
    // 根据扫码结果添加或更新商品到商品列表
    await addOrUpdateProductByBarcode(res.result);
  } catch (err) {
    console.error('Detailed scan error:', err.errMsg);
  }
}
// 添加或更新商品的方法
async function addOrUpdateProductByBarcode(barcode) {
  // 尝试找到具有相同条码的商品
  let productIndex = products.value.findIndex(product => product.barcode === barcode);
  if (productIndex !== -1) {
    // 如果找到了，更新数量和总价
    products.value[productIndex].qutity += 1;
    products.value[productIndex].total = products.value[productIndex].qutity * products.value[productIndex].retailPrice;
  } else {
    // 如果没有找到，根据barcode查询商品详情，向服务器发起请求获取商品详情
    try {
      const response = await fetchProductDetails(barcode);
      if (!response.data || response.data.length === 0) { // 判断返回的列表是否为空
        throw new Error("No product found");
      }
      const data = response.data[0]; // 获取第一个匹配的商品信息
      // 使用从服务器获取的商品信息，创建新商品对象
      const newProduct = {
        productName: data.productName,
        barcode: barcode,
        qutity: 1,
        retailPrice: data.retailPrice,
        total: data.retailPrice,
        productId: data.productId,
		productImageUrl:productImageUrl
      };
      products.value.push(newProduct);
    } catch (error) {
      if (error.message === "No product found") {
        uni.showToast({
          title: '商城此商品已下架',
          icon: 'none',
          duration: 2000
        });
      } else {
        console.error("Error fetching product details:", error.message);
        uni.showToast({
          title: '网络请求失败，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
// 发起网络请求获取商品详情  192.168.129.92
function fetchProductDetails(barcode) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `http://localhost:15000/PRODUCT-SERVICE/product/search?query=${encodeURIComponent(barcode)}`,
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res);
        } else {
          reject(new Error(`Server responded with status code ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg));
      }
    });
  });
}
const handlePaymentSuccess = (data) => {
  // 清空商品列表
  // products.value = [];
  store.dispatch('clearProducts')
  totalProducts.value = 0;
  searchVal.value = ''; // 直接清空 v-model 绑定的值
  // 可选：显示详细收银信息
  uni.showToast({
    title: `通过【${data.method}】完成支付，实收：¥${data.amount.toFixed(2)}，找零：¥${data.change}`,
    icon: 'success',
    duration: 3000
  });
};

//携带商品参数跳转到配送页面
// function handleDeliverySelection(path) {
//   // 收集所有商品的 id 和数量
//   const selectedItems = products.value.map(product => ({
//     productId: product.productId,
//     qutity: product.qutity
//   }));
//   console.log(selectedItems)
//   // 使用 uni.navigateTo 跳转页面，并传递所选商品的信息
//   uni.navigateTo({
//     url: `${path}?items=${encodeURIComponent(JSON.stringify(selectedItems))}` // 将对象数组转换为字符串并编码
//   });
// }
function handleDeliverySelection(path) {
	if (products.value.length > 0) {
	  // 收集所有商品的 id、数量、名称、单价和总价
	  const selectedItems = products.value.map(product => ({
	    productId: product.productId,
	    quantity: product.qutity,
	    name: product.productName,
	    price: product.retailPrice,
		productImageUrl:product.productImageUrl
	  }));
	  // 使用 Vuex 存储商品列表信息
	  store.dispatch('updateCart', selectedItems);
	  // 遍历并打印每个商品的信息
	    selectedItems.forEach((item, index) => {
	      console.log(`Item ${index + 1}:`);
	      console.log('Product ID:', item.productId);
	      console.log('Quantity:', item.quantity);
	      console.log('Name:', item.name);
	      console.log('Price:', item.price);
		  console.log('productImageUrl：',item.productImageUrl)
	    });
	  // 跳转到配送页面
	  uni.navigateTo({
	  	url:path
	  })
	} else {
	  uni.showToast({
	    title: '请添加商品',
	    icon: 'error',
	    duration: 2000
	  });
	}
}
</script>

<style scoped>
.checkout-page {
  width: 100%;
  height: 90vh; /* 确保至少占满整个视口高度 */
  background-color: #f3f4f6;
  display: flex;
  flex-direction: column;
}
.content-container {
  width: 100%;
  flex: 1;
  overflow-y: auto;
  background-color: #f3f4f6;
  padding-bottom: 30px;
}
.search-bar {
  margin-top: 1px;
  border-top: 1px solid gainsboro;
  padding: 0px;
  height: 70px;
  line-height: 70px;
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #f3f4f6; /* 与背景颜色一致，避免视觉上的突兀 */
}
/* 添加样式以支持商品列表头部 */
.product-header {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px;
  background-color: #e6e6e6;
  font-weight: bold;
  position: sticky;
  top: 70px; /* 与 .search-bar 的高度相匹配 */
  z-index: 10;
}

.header-item {
  text-align: center;
}
.header-item.name-code {
  width: 28%; /* 根据实际需要调整 */
}
.product-item {
  border-radius: 10px;
  font-size: 16px;
  margin: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 修改为flex-start以适应顶部对齐 */
  padding: 13px;
  border-bottom: 1px solid #ddd;
  background-color:#fff ;
}

.product-info {
  width: 38%; /* 调整宽度以适应两个文本行 */
  display: flex;
  flex-direction: column;
}

/* 确保商品名称在超过指定宽度时显示省略号 */
.product-name {
  width: 100%;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-code {
  width: 100%;
  box-sizing: border-box;
  color: #a4a4a4;
  padding-top: 5px;
}
.product-total{
  word-break: break-all; /* 允许长单词或URL地址换行到下一行 */
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
}
.product-quantity, .product-price, .product-total {
  width: 16%; /* 100% / 6 (考虑到有4个主要区域 + 空隙)，适当调整 */
  text-align: center;
  padding-top: 27px;
}

.summary {
  margin:0px 15px 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}
.clear-button {
  margin-left: 10px;
  cursor: pointer;
}

.order-notes {
  color: #0059df;
  margin:0px 15px 15px 15px;
}

.footer {
  position: fixed;
  bottom: 50px;
  left: 0;
  right: 0;
  background-color: white;
  padding: 10px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  z-index: 990;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.delivery-method,
.settlement {
  width: 45%;
  height: 50px;
  border-radius: 8px;
  font-size: 18px;
  text-align: center;
  line-height: 50px;
  background-color: #007aff;
  color: #fff;
}

.delivery-method {
  background-color: #ddd;
  color: #333;
}
/* 没有商品的时候，添加 no-products-tip 样式 */
.no-products-tip {
  text-align: center;
  font-size: 16px;
  color: #565656;
  margin-top: 180px;
}

.pull-down-scan {
  font-size: 24px;
  font-weight: bold;
  color: #035be0;
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: center;
  margin-top: 200px;
}

.pull-down-scan image {
  width: 70px;
  height: 70px;
}
</style>